package com.test.travelinformation.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.test.travelinformation.R;
import com.test.travelinformation.entity.User;
import com.test.travelinformation.utils.SPUtils;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 请输入用户名
     */
    private EditText mEditLoginName;
    /**
     * 请输入密码
     */
    private EditText mEditLoginPassword;
    /**
     * 登录
     */
    private Button mBtnLogin;
    /**
     * 注册
     */
    private Button mBtnSign;
    private LinearLayout mLlUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initData();
    }


    private void initView() {
        mEditLoginName =  findViewById(R.id.edit_login_name);
        mEditLoginPassword = findViewById(R.id.edit_login_password);
        mBtnLogin =  findViewById(R.id.btn_login);
        mBtnLogin.setOnClickListener(this);
        mBtnSign =  findViewById(R.id.btn_sign);
        mBtnSign.setOnClickListener(this);
        mLlUserInfo = findViewById(R.id.ll_user_info);
    }

    private void initData(){

    }

    private void login(){
        String name = mEditLoginName.getText().toString();
        String password = mEditLoginPassword.getText().toString();
        User user = new User();
        user.setUsername(name);
        user.setPassword(password);
        user.login(new SaveListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e == null){
                    SPUtils.put(LoginActivity.this,"userId",user.getObjectId());
                    SPUtils.put(LoginActivity.this,"username",user.getUsername());
                    Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    LoginActivity.this.finish();
                }else {
                    Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.btn_sign:
                startActivity(new Intent(this,SignActivity.class));
                break;
        }
    }

}
